﻿using SBlogCore.Common.CacheExtend.MemoryCacheExtension;
using SBlogCore.Common.CacheExtend;

namespace SBlogCore.WebAdminApplication.SysManager.CacheServices
{

    public class MenuCacheService: IMenuCacheService
    {
        private readonly ISBlogCoreCache _memoryCache; 

        public MenuCacheService(ISBlogCoreCache memoryCache)
        {
            this._memoryCache = memoryCache;
        }
        //Key前缀    
        private readonly string _preKey="menu*";
        /// <summary>
        /// 获取菜单缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public  Task<T?> GetMenu<T>(string key)
        {
            key=$"{_preKey}{key}";
            return _memoryCache.GetAsync<T>(key);
        }
        /// <summary>
        /// 获取或者创建菜单缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="valueFactory"></param>
        /// <returns></returns>
        public Task<T?> GetOrCreateMenu<T>(string key, Func<Task<T>>? valueFactory = null)
        {
            key = $"{_preKey}{key}";
            return _memoryCache.GetOrCreateAsync(key, valueFactory);    
        }
        /// <summary>
        /// 存储菜单缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public Task SetMenu<T>(string key,T data)
        {
            key = $"{_preKey}{key}";
           return _memoryCache.CreateAsync(key, data);
        }
        /// <summary>
        /// 删除指定key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Task DeleteMenu(string key)
        {
            key = $"{_preKey}{key}";
           return _memoryCache.RemoveAsync(key);
        }
        /// <summary>
        /// 清楚所有的缓存
        /// </summary>
        /// <returns></returns>
        public Task ClearMenu()
        {
            return _memoryCache.RemoveByPatternAsync(_preKey);
        }
    }
}
